#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
综合测试脚本 - 测试应用的各项功能
"""

import sys
import os
import unittest

TEST_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'sqlite:///:memory:')
os.environ['DATABASE_URL'] = TEST_DATABASE_URI

from app_main import app, db
from models import UserActual, HouseInfoFinal

class FlaskAppTestCase(unittest.TestCase):
    def setUp(self):
        """测试前准备"""
        app.config['TESTING'] = True
        self.app = app.test_client()
        with app.app_context():
            db.session.remove()
            db.create_all()
            UserActual.query.filter_by(name='testuser').delete()
            HouseInfoFinal.query.filter_by(title='测试房源').delete()
            db.session.commit()

            # 创建测试数据
            test_user = UserActual(
                name='testuser',
                password='testpass',
                email='test@example.com',
                addr='北京市朝阳区',
                collect_id='',
                seen_id=''
            )
            db.session.add(test_user)
            db.session.commit()
            
            # 创建测试房源数据
            test_house = HouseInfoFinal(
                title='测试房源',
                rooms='2室1厅',
                area='80平米',
                price='5000元/月',
                direction='朝南',
                rent_type='整租',
                region='北京市朝阳区',
                block='三里屯',
                address='北京市朝阳区三里屯大街1号',
                traffic='地铁10号线团结湖站',
                publish_time=1609459200,  # 2021-01-01
                facilities='冰箱,洗衣机,空调,电视',
                highlights='交通便利,采光好',
                matching='周边配套齐全',
                travel='距离地铁站500米',
                page_views=100,
                landlord='张三',
                phone_num='13800138000',
                house_num='BJ20210101001'
            )
            db.session.add(test_house)
            db.session.commit()

    def tearDown(self):
        """测试后清理"""
        with app.app_context():
            db.session.remove()
            UserActual.query.filter_by(name='testuser').delete()
            HouseInfoFinal.query.filter_by(title='测试房源').delete()
            db.session.commit()

    def test_index_page(self):
        """测试首页"""
        response = self.app.get('/')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'<!DOCTYPE html>', response.data)

    def test_login_page(self):
        """测试登录页面"""
        response = self.app.get('/login')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'<!DOCTYPE html>', response.data)

    def test_register_page(self):
        """测试注册页面"""
        response = self.app.get('/register')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'<!DOCTYPE html>', response.data)

    def test_health_check(self):
        """测试健康检查接口"""
        response = self.app.get('/health')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'healthy', response.data)

    def test_user_model_methods(self):
        """测试用户模型方法"""
        with app.app_context():
            user = UserActual.query.first()
            self.assertIsNotNone(user)
            
            # 测试收藏功能
            user.add_to_collection(1)
            self.assertTrue(user.is_collected(1))
            
            # 测试取消收藏
            user.remove_from_collection(1)
            self.assertFalse(user.is_collected(1))
            
            # 测试浏览记录
            user.add_to_seen(1)
            seen_ids = user.get_seen_ids()
            self.assertIn('1', seen_ids)
            
            # 测试清空浏览记录
            user.clear_seen()
            self.assertEqual(user.seen_id, '')

    def test_house_model_methods(self):
        """测试房源模型方法"""
        with app.app_context():
            # 测试获取房源总数
            total_count = HouseInfoFinal.get_total_count()
            self.assertGreater(total_count, 0)
            
            # 测试获取推荐房源
            recommended = HouseInfoFinal.get_recommended_houses()
            self.assertIsInstance(recommended, list)
            
            # 测试获取热点房源
            hot_houses = HouseInfoFinal.get_hot_houses()
            self.assertIsInstance(hot_houses, list)

if __name__ == '__main__':
    print("开始运行综合测试...")
    unittest.main(verbosity=2)
